/**
 * @author Created by qiush on 2017-06-09.
 */

const {ipcMain} = require('electron');

const fileUtil = require('./fileUtil');
const dialogUtil = require('./dialogUtil');
const resourceUtil = require('./resourceUtil');
const designResourceUtil = require('./designResourceUtil');

const designFiles = {};

function _parseDesign(fileData) {
  try {
    return JSON.parse(fileData);
  } catch (e) {
    dialogUtil.showError(e);
  }
}

async function _getDesignFilename(designId) {
  if (designFiles[designId]) {
    return Promise.resolve(designFiles[designId]);
  }

  const filename = await dialogUtil.showSave({
    title: '保存文件',
    filters: [{
      name: '页面配置文件',
      extensions: ['page']
    }]
  });
  designFiles[designId] = filename;
  return filename;
}

const designFileUtil = {
  /**
   *
   * @param filename
   * @returns {Promise}
   */
  async open(filename) {

    const fileData = await fileUtil.readFile(filename);

    const designFileContent = _parseDesign(fileData);
    if (!designFileContent) {
      return Promise.reject('不能正确解析文件, 请确定选择的是正确的设计文件?');
    }

    const design = designFileContent.design;

    // 处理资源
    resourceUtil.addResources(designFileContent.resources);

    // 保存设计文件的路径, 用于后续的保存
    designFiles[design.id] = filename;

    return design;
  },

  async save(design) {
    if (!design || !design.id) {
      return Promise.reject('不是正确的设计内容...');
    }

    const designResources = designResourceUtil.findDesignResources(design);

    const designFileContent = {
      design,
      resources: designResources
    };

    const designFilename = await _getDesignFilename(design.id);
    return fileUtil.writeFile(designFilename, designFileContent);
  }
};

ipcMain.on('save-file', (event, design) => {
  designFileUtil.save(design)
    .then(filePath => {
      // 要通知一下页面文件已保存, 更新一下标题栏的名称
      const filename = fileUtil.filename(filePath);
      event.sender.send('saved-file', design.id, filename)
    })
    .catch(dialogUtil.showError);
});

module.exports = designFileUtil;
